package com.example.demo.socket;


import com.alibaba.fastjson.JSONObject;
import com.example.demo.core.exception.ProgramException;
import com.example.demo.core.util.JsonUtil;
import com.example.demo.core.util.RegexUtil;
import com.example.demo.core.util.ThreadUtil;
import com.example.demo.socket.channelManager.MobileSocketManager;
import com.example.demo.socket.handler.SocketMessageHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;


/**
 * @author yj
 * @date 2021/4/6 13:40
 */
@Component
@Sharable
@Slf4j
public class SocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    private SocketMessageHandler socketMessageHandler;

    /**
     * 注册
     *
     * @param ctx
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        String shortId = channel.id().asShortText();
        String hostAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
        log.info("当前注册链接来自{},链接ID是：{}", hostAddress, shortId);
    }

    /**
     * 连接成功
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        String shortId = channel.id().asShortText();
        MobileSocketManager.save(channel, shortId);
    }

    /**
     * 读消息
     *
     * @param channelHandlerContext
     * @param textWebSocketFrame
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) {
        Channel channel = channelHandlerContext.channel();
        String shortId = channel.id().asShortText();
        String value = textWebSocketFrame.text();
        try {
            socketMessageHandler.messageHandle(
                    shortId,
                    JsonUtil.jsonObjectToType(
                            value,
                            JSONObject.class
                    )
            );
        } catch (Exception e) {
            log.error("{}异常出现在链接ID：{}，出异常：{},异常数据：{}", ThreadUtil.getMethodName(), shortId, e.getMessage(), value);
        }
    }

    /**
     * 异常
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel channel = ctx.channel();
        String shortId = channel.id().asShortText();
        log.error("链接：{}出现异常，异常信息为：{}", shortId, cause.getMessage());
    }

    /**
     * 客户端主动断开连接
     *
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        String shortId = channel.id().asShortText();
        log.error("链接：{}主动断开链接", shortId);
    }

    /**
     * 断开的最终处理处
     *
     * @param ctx
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        String shortId = channel.id().asShortText();
        log.error("链接：{}最终断开链接方法", shortId);
        MobileSocketManager.remove(shortId);
    }


}